package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWLXAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class NEWLXAPIImpl implements NEWLXAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"1",salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.doPostForm(salePartner.getOther(),params,null);
        log.info("流星添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("流星添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("msg");
        if (!Objects.isNull(resultJson)) {
            if (!"0".equals(resultJson.getString("code"))&&!msg.contains("该商品已存在")) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                if(msg.contains("该商品已存在")){
                    editGame(goodsInfoAndAttrValueDto,salePartner);
                }
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                if (CollectionUtils.isNotEmpty(artRecs)) {
                    artRecs.get(0).setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                    artRecMapper.updateArtRec(artRecs.get(0));
                } else {
                    artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                    artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                    artRecreq.setType(LCConstant.interAdd);
                    artRecreq.setConfig(salePartner.getId());
                    artRecreq.setSaleCode(salePartner.getSaleName());
                    artRecreq.setOutid(String.valueOf(goodsInfoAndAttrValueDto.getId()));
                    artRecMapper.insertArtRec(artRecreq);
                }
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "添加失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"2",salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.doPostForm(salePartner.getOther(),params,null);
        log.info("流星修改接口请求参数={}", JSONObject.toJSONString(params));
        log.info("流星修改接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"0".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "编辑失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String type,SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        params.put("operation", type);
        params.put("ensureOpen", "1");
        params.put("securitService", "5,6,4,8");
        params.put("apiSuffix", salePartner.getTwoOther());
        if(!type.equals("1")){
            if(type.equals("2")) {
                params.put("showSign", 0);
            }else {
                params.put("showSign", 2);
            }
        }
        params.put("goodsTypeId", "1");
        if(goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")) {
            params.put("gameId", "3");
            if(goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("areaId", "108");
                    params.put("serverId", "4039");
                }else{
                    params.put("areaId", "107");
                    params.put("serverId", "4038");
                }
            }else{
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("areaId", "109");
                    params.put("serverId", "4040");
                }else{
                    params.put("areaId", "106");
                    params.put("serverId", "4037");
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("和平精英")) {
            params.put("gameId", "56");
            if(goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                params.put("areaId", "185");
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("serverId", "8052");
                }else{
                    params.put("serverId", "8051");
                }
            }else{
                params.put("areaId", "184");
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("serverId", "8050");
                }else{
                    params.put("serverId", "8049");
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
            params.put("gameId", "64");
            if(goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                params.put("areaId", "176");
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("serverId", "4036");
                }else{
                    params.put("serverId", "4035");
                }
            }else{
                params.put("areaId", "175");
                if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                    params.put("serverId", "4034");
                }else{
                    params.put("serverId", "4033");
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("原神")){
            params.put("gameId", "69");
            if(goodsInfoAndAttrValueDto.getCarrierName().equals("游戏官方")){
                params.put("areaId", "282");
                params.put("serverId", "8102");
            }else{
                params.put("areaId", "330");
                params.put("serverId", "8527");
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("火影忍者")){
            params.put("gameId", "61");
            String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regional.equals("安卓QQ")) {
                params.put("areaId", "183");
                params.put("serverId", "7049");
            }else if(regional.equals("安卓微信")){
                params.put("areaId", "181");
                params.put("serverId", "5049");
            }else if(regional.equals("苹果QQ")){
                params.put("areaId", "182");
                params.put("serverId", "6055");
            }else{
                params.put("areaId", "180");
                params.put("serverId", "4049");
            }
        }
        params.put("goodsNum","1");
        String bigTitle = "";
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitle())){
            bigTitle = goodsInfoAndAttrValueDto.getTitle().replace("*","").replace("+","");
        }else if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getDes())){
            bigTitle = goodsInfoAndAttrValueDto.getDes().replace("*","").replace("+","");
        }
        if(bigTitle.length()>1000){
            bigTitle = bigTitle.substring(0,800);
        }else{
            bigTitle = bigTitle;
        }

        params.put("bigTitle","【"+descTitle+"_"+goodsInfoAndAttrValueDto.getId()+"】"+bigTitle);
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), salePartner);
        params.put("price", bigDecimal.intValue());
        String goodsDecs = "";
        if(goodsInfoAndAttrValueDto.getDes().length()>1500){
            goodsDecs = goodsInfoAndAttrValueDto.getDes().substring(0,1400).replace("*","");
        }else{
            goodsDecs = goodsInfoAndAttrValueDto.getDes().replace("*","");
        }
        params.put("goodsDecs","【"+descTitle+"_"+goodsInfoAndAttrValueDto.getId()+"】"+goodsDecs.replace("+",""));
        params.put("thumbnail", goodsInfoAndAttrValueDto.getTitleImg()==null?LCConstant.defaultImg:goodsInfoAndAttrValueDto.getTitleImg());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String pic = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            pic = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            pic = LCConstant.defaultImg;
        }
        params.put("goodsImages", pic);
        params.put("outSn", goodsInfoAndAttrValueDto.getId());
        String cover = MapUntils.getCover(params);
        String covers = cover+"key="+salePartner.getSaleKey();
        System.out.println("加密参数==="+covers);
        String sign = DigestUtils.md5Hex(covers);
        params.put("sign",sign);
        return params;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        List<GameAttribute> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids)) {
            list = gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                    Long.class));
        }
        return list;
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"3",salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpUtils.doPostForm(salePartner.getOther(),params,null);
        log.info("流星删除接口请求参数={}", JSONObject.toJSONString(params));
        log.info("流星删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (!Objects.isNull(resultJson)) {
            if (!"0".equals(resultJson.getString("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        if (CollectionUtils.isNotEmpty(artRecs)) {
            artRecMapper.deleteArtRecById(artRecs.get(0).getId());
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);

        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        Map<String,String> param = new HashMap<>();
        param.put("gameId","3");
        String response = HttpUtil.doGet("http://ff.cyjh.co/api/comm/gamefilter", param, null);
        System.out.println(response);
    }



}
